package com.atguigu.gmall.product.service.impl;

import com.atguigu.gmall.common.util.DateUtil;
import com.atguigu.gmall.common.config.minio.AppMinioProperties;
import com.atguigu.gmall.product.service.FileUploadService;
import io.minio.MinioClient;
import io.minio.PutObjectOptions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.UUID;

/**
 * SPH_Demo01
 * 2022/11/3 12 51
 */
@Service
public class FileUploadServiceImpl implements FileUploadService {

    @Autowired
    AppMinioProperties appMinioProperties;

    @Autowired
    MinioClient minioClient;


    /**
     * 文件上传到Minio中，并且返回url数据
     * @param multipartFile：文件
     * @return Minio中文件的Url
     * @throws Exception：上传失败
     */
    @Override
    public String fileUpload (MultipartFile multipartFile) throws Exception {
        //String url = "http://192.168.6.131:9000";

        if (!minioClient.bucketExists (appMinioProperties.getBucket ())){
            minioClient.makeBucket (appMinioProperties.getBucket ());
        }

        String date = DateUtil.formatDate (new Date ());
        String originalFilename =date + "/" + UUID.randomUUID ().toString ().replace ("-","") + "_" + multipartFile.getOriginalFilename ();
        PutObjectOptions objectOptions = new PutObjectOptions (multipartFile.getSize (), -1);

        //带上传类型一起进行上传
        objectOptions.setContentType (multipartFile.getContentType ());
        minioClient.putObject (appMinioProperties.getBucket (), originalFilename,multipartFile.getInputStream (),objectOptions);

        return appMinioProperties.getEndpoint () + "/" + appMinioProperties.getBucket () + "/" + originalFilename;
    }
}
